package org.example.everyday;

public class MyCircularQueue {
    private int front;
    private int rear;
    private int capacity;
    private int[] elements;

    public MyCircularQueue(int k) {
        this.capacity = k + 1;
        elements = new int[capacity];
        rear = front = 0;
    }

    /**
     * 在队列的尾部插入一个元素，并同时将队尾的索引rear更新为(rear+1) mod capacity
     * @param value
     * @return
     */
    public boolean enQueue(int value){
        if(isFull()){
            return false;
        }
        elements[rear] = value;
        rear = (rear + 1) % capacity;
        return true;
    }

    /**
     * 从队首取出一个元素，并同时将队首的索引front更新为(front+1) mod capacity
     * @return
     */
    public boolean deQueue(){
        if(isEmpty()){
            return false;
        }
        front = (front + 1) % capacity;
        return true;
    }

    public int Front(){
        if(isEmpty()){
            return -1;
        }
        return elements[front];
    }

    public int Rear(){
        if(isEmpty()){
            return -1;
        }
        return elements[(rear - 1 + capacity) % capacity];
    }

    public boolean isEmpty(){
        return rear == front;
    }

    public boolean isFull(){
        return ((rear + 1) % capacity) == front;
    }

    public static void main(String[] args) {
        // 设置长度为 3
        MyCircularQueue circularQueue = new MyCircularQueue(3);
        circularQueue.enQueue(1);
        circularQueue.enQueue(2);
        circularQueue.enQueue(3);
        // 返回 false，队列已满
        circularQueue.enQueue(4);
        circularQueue.Rear(); // 返回 3
        circularQueue.isFull(); // 返回 true
        circularQueue.deQueue();
        // 返回 true
        circularQueue.enQueue(4);
        circularQueue.Rear(); // 返回 4

    }
}
